import React from 'react';
import { Card, Table, Divider, Modal, Button, Form, Input, Radio, Icon, message, DatePicker, Pagination, Upload, Select, Spin, Popover } from 'antd';
import { NavLink } from 'react-router-dom';
import moment from 'moment';
import ResizeableTitle from '@/utils/resizeableTitle';
import Utils from '@/utils/utils';
import '@/style/style.css';
import { mobileRegex, telRegex, idCardRegex, UploadBaseUrl } from '@/utils/globalConst';
import Axios from "@/axios";
import { fileDirectory } from "@/config/systemConfig";
import UploadImage from "@/components/UploadImage";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;

export default class UserList extends React.Component {
    state = {
        columns: [{
            title: '序号',//用户自编号码
            dataIndex: 'userNo',
            width: 100,
        }, {
            title: '帐号',
            dataIndex: 'account',
            width: 100,
        }, {
            title: '姓名',
            dataIndex: 'name',
            width: 100,
        }, {
            title: '性别',
            dataIndex: 'gender',
            width: 100,
            render(gender) {
                let config = {
                    'SECRECY': '保密',
                    'MAN': '男',
                    'WOMAN': '女',
                }
                return config[gender];
            }
        }, {
            title: '年龄',
            dataIndex: 'age',
            width: 100,
            render(text) {
                return <span>{text >= 0 ? text : '—'}</span>;
            }
        }, {
            title: '身份证',
            dataIndex: 'idcard',
            width: 200,
            render(text) {
                return <span>{text ? Utils.formatIdentity(text) : "—"}</span>;
            }
        }, {
            title: '学历',
            dataIndex: 'eduBackground',
            width: 100,
            render(text) {
                return <span>{text ? text : '—'}</span>;
            }
        }, {
            title: '职位',
            dataIndex: 'position',
            width: 100,
            render(text) {
                return <span>{text ? text : '—'}</span>;
            }
        }, {
            title: '职称',
            dataIndex: 'jobTitle',
            width: 100,
            render(text) {
                return <span>{text ? text : '—'}</span>;
            }
        }, {
            title: '领域从业年限',
            dataIndex: 'serviceYear',
            width: 100,
            render(text) {
                return <span>{text ? text : '—'}</span>;
            }
        }, {
            title: '部门',
            dataIndex: 'depts',
            width: 100,
        }, {
            title: '岗位',
            dataIndex: 'jobs',
            width: 100,
        }, {
            title: '入职时间',
            dataIndex: 'hiredate',
            width: 200,
            render(text) {
                return <span>{text ? moment(text).format("YYYY-MM-DD") : '—'}</span>;
            }
        }, {
            title: '操作',
            key: 'action',
            render: (text, record, index) => (
                <span>
                    <NavLink className="btn-txt-primary" to={`/organMember/user/userDetails/${record.id}`}>查看详情</NavLink>
                    <Divider type="vertical" />
                    {record.state == "VALID" ? <a href="javascript:;" onClick={() => this.handleUpdateState(record, "DISABLE")} className="btn-txt-danger">禁用</a> : ''}
                    {record.state == "DISABLE" ? <a href="javascript:;" onClick={() => this.handleUpdateState(record, "VALID")} className="btn-txt-primary">激活</a> : ''}
                    {record.state == "INACTIVE" ? <a href="javascript:;" onClick={() => this.handleUpdateState(record, "VALID")} className="btn-txt-primary">激活帐号</a> : ''}
                    <Divider type="vertical" />
                    <span>
                        <Popover content={
                            <div className="btn-group-box">
                                <div><a href="javascript:;" onClick={() => this.handleUpdateInfo(record)} className="btn-txt-primary">更新信息</a></div>
                                <div><a href="javascript:;" onClick={() => this.handleResetPwd(record)} className="btn-txt-primary">重置密码</a></div>
                                <div><a href="javascript:;" onClick={() => this.handleUpdateState(record, "DELETE")} className="btn-txt-danger">删除</a></div>
                            </div>
                        }
                            trigger="focus"
                            placement="bottom"
                        >
                            <a href="javascript:;" className="btn-txt-primary">
                                更多操作 <Icon type="down" />
                            </a>
                        </Popover>
                    </span>
                </span>
            ),
        }],
        createModal: {
            visible: false,
            confirmLoading: false,
        },
        resetPwdModal: {
            visible: false,
            confirmLoading: false,
        },
        updateInfoModal: {
            visible: false,
            confirmLoading: false,
        },
        userNo: "",//自定义用户序号
    };
    initParams = {
        max: 10,
        keywords: '',
        page: 1,
        state: '',
    }
    componentWillMount() {
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params);
    }
    //搜索
    handleFilter = (fieldsValue) => {
        const values = {
            ...fieldsValue,
        };
        //console.log(values);
        this.initParams = {
            ...this.initParams,
            ...values,
            page: 1
        }
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params)
    }
    //创建    会拉取自定义用户序号 ， 拉取到数据自动填入序号，否则用户自己输入
    handleCreate = () => {
        //console.log("0000")
        this.getUserNoRequest();
        this.setState({
            createModal: {
                ...this.state.createModal,
                visible: true
            }
        })
    }
    //创建用户确定
    handleCreateSubmit = () => {
        const _form = this.createForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            //console.log(values);
            let params = Utils.FilterParam(values);
            //console.log(params)
            this.createUserRequest(params);
        });
    }
    //更新用户信息 表单
    handleUpdateInfo = (record) => {
        this.setState({
            updateInfoModal: {
                ...this.state.updateInfoModal,
                visible: true
            },
            updateInfo: {
                ...record,
            }
        })
    }
    //更新用户信息 表单提交
    handleUpdateInfoSubmit = () => {
        const _form = this.updateInfoForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            const birthDate = values['birthDate'] ? values['birthDate'].format('YYYY-MM-DD') : '';
            const beginIndustryJobTime = values['beginIndustryJobTime'] ? values['beginIndustryJobTime'].format('YYYY-MM-DD') + ' 00:00:00' : '';
            const hiredate = values['hiredate'] ? values['hiredate'].format('YYYY-MM-DD') + ' 00:00:00' : '';
            let params = {
                ...values,
                birthDate,
                beginIndustryJobTime,
                hiredate,
            }
            params = Utils.FilterParam(params);
            //console.log(params)
            this.updateUserRequest(params);
        });
    }
    //更新用户状态
    handleUpdateState = (record, state) => {
        let stateTxt = "";
        switch (state) {
            case "DISABLE":
                stateTxt = "禁用";
                break;
            case "VALID":
                stateTxt = "激活";
                break;
            case "DELETE":
                stateTxt = "删除";
                break;
        }
        let params = {
            id: record.id,
            state,
        }
        Modal.confirm({
            title: `确认${stateTxt}`,
            content: <div>
                {state == 'DISABLE' ? <div className="txt-danger">确认禁用该账户？</div> : ''}
                {state == 'VALID' ? <div className="txt-danger">确认激活该账户？</div> : ''}
                {state == 'DELETE' ? <div className="txt-danger">确认删除该账户？删除后数据不可恢复！</div> : ''}
            </div>,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                //console.log(record.id)
                this.setState({
                    loading: true,
                    loadingTxt: `${stateTxt}中...`
                })
                Axios.put({
                    block: '/hr',
                    url: '/user/updateState',
                    params: params,
                }).then((data) => {
                    //console.log(data);
                    this.setState({ loading: false })
                    let _params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    message.success(`${stateTxt}成功`, 2, () => {
                        this.listRequest(_params);
                    });
                }).catch((error) => {
                    this.setState({ loading: false })
                    console.log(error);
                })
            }
        })
    }
    //重置密码 表单
    handleResetPwd = (record) => {

        this.setState({
            resetPwdModal: {
                ...this.state.resetPwdModal,
                visible: true
            },
            resetInfo: {
                ...record,
            }
        })
    }
    //重置密码 表单提交
    handleResetPwdSubmit = () => {
        const _form = this.resetPwdForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            let params = Utils.FilterParam(values);
            this.setState({
                resetPwdModal: {
                    ...this.state.resetPwdModal,
                    confirmLoading: true,
                }
            })
            Axios.put({
                block: '/hr',
                url: '/user/resetPwd',
                params: params,
            }).then((data) => {
                //console.log(data)
                this.setState({
                    resetPwdModal: {
                        ...this.state.resetPwdModal,
                        visible: false,
                        confirmLoading: false,
                    }
                }, () => {
                    _form.resetFields();
                    message.success('密码重置成功！', 2, () => {
                        let _params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                        this.listRequest(_params);
                        //window.location.reload()
                    });
                })
            }).catch((error) => {
                console.log(error);
                this.setState({
                    resetPwdModal: {
                        ...this.state.resetPwdModal,
                        confirmLoading: false,
                    }
                })
            })
        });
    }
    //重置密码 表单取消
    handleResetPwdCancle = () => {
        const _form = this.resetPwdForm.props.form;
        this.setState({
            resetPwdModal: {
                ...this.state.resetPwdModal,
                visible: false
            }
        }, () => { _form.resetFields(); })
    }
    //用户列表  请求
    listRequest = (params) => {
        let _this = this;
        this.setState({
            loading: true,
            loadingTxt: '加载中...'
        })
        Axios.get({
            block: '/hr',
            url: '/user',
            params,
        }).then((data) => {
            //console.log(data)
            let page = data.page;
            let dataSource = data.data;
            dataSource.map((item) => {
                item.key = item.id;
                return item;
            })
            this.setState({
                loading: false,
                dataSource,
                pagination: Utils.pagination(page, (current) => {
                    _this.initParams.page = current;
                    let params = this.initParams;
                    _this.listRequest(params);
                }, (current, pageSize) => {
                    _this.initParams.page = current;
                    _this.initParams.max = pageSize;
                    let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    _this.listRequest(params);
                })
            })
        }).catch((error) => {
            this.setState({ loading: false })
            console.log(error);
        })
    }
    //获取自定义用户序号请求
    getUserNoRequest = () => {
        let params = {
            key: 'hr_user_no'
        }
        this.setState({
            loading: true,
            loadingTxt: '获取自定义用户序号中...'
        })
        Axios.get({
            block: '/setting',
            url: '/objectNo/nextNo',
            params: params,
        }).then((data) => {
            // console.log(data)
            let userNo = data.data;
            this.setState({
                loading: false,
                userNo
            })
        }).catch((error) => {
            this.setState({ loading: false })
            console.log(error);
        })
    }
    /*创建用户请求*/
    createUserRequest = (params) => {
        this.setState({
            createModal: {
                ...this.state.createModal,
                confirmLoading: true,
            }
        })
        Axios.post({
            block: '/hr',
            url: '/user',
            params: params,
        }).then((data) => {
            //console.log(data)
            this.setState({
                createModal: {
                    ...this.state.createModal,
                    visible: false,
                    confirmLoading: false,
                }
            }, () => {
                message.success('创建成功！', 2, () => {
                    //this.listRequest(_this.initParams);
                });
                window.location.reload()
            })
        }).catch((error) => {
            console.log(error);
            this.setState({
                createModal: {
                    ...this.state.createModal,
                    confirmLoading: false,
                }
            })
        })
    }
    /*更新用户请求*/
    updateUserRequest = (params) => {
        this.setState({
            updateInfoModal: {
                ...this.state.updateInfoModal,
                confirmLoading: true,
            }
        })
        Axios.put({
            block: '/hr',
            url: '/user',
            params: params,
        }).then((data) => {
            //console.log(data)
            this.setState({
                updateInfoModal: {
                    ...this.state.updateInfoModal,
                    visible: false,
                    confirmLoading: false,
                }
            }, () => {
                message.success('资料更新成功！', 2, () => {
                    //window.location.reload()
                });
                let _params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                this.listRequest(_params);
            })
        }).catch((error) => {
            console.log(error);
            this.setState({
                updateInfoModal: {
                    ...this.state.updateInfoModal,
                    confirmLoading: false,
                }
            })
        })
    }
    //伸缩列
    components = {
        header: {
            cell: ResizeableTitle
        },
    };
    handleResize = index => (e, { size }) => {
        this.setState(({ columns }) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return { columns: nextColumns };
        });
    };
    render() {
        const columns = this.state.columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        return (
            <div className="tab-list-box">
                <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                    <Card
                        title="用户列表"
                        bordered={false}>
                        <div style={{ marginBottom: 15 }}>
                            <div className="filter-box" style={{ textAlign: 'left', marginBottom: 15 }}>
                                <FilterForm filterSubmit={(fieldsValue) => { this.handleFilter(fieldsValue) }} />
                            </div>
                            <div style={{ textAlign: 'right', marginBottom: 15 }}><Button type="primary" icon="plus" onClick={this.handleCreate}>创建用户</Button></div>
                        </div>
                        <Table
                            bordered
                            components={this.components}
                            columns={columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                        />
                    </Card>
                </Spin>
                <Modal title="创建用户"
                    visible={this.state.createModal.visible}
                    onOk={this.handleCreateSubmit}
                    okText="创建"
                    confirmLoading={this.state.createModal.confirmLoading}
                    destroyOnClose={true}
                    onCancel={() => {
                        this.setState({
                            createModal: {
                                visible: false
                            }
                        })
                    }}
                >
                    <CreateForm userNo={this.state.userNo} wrappedComponentRef={(createForm) => { this.createForm = createForm; }} />
                </Modal>
                <Modal title="密码重置"
                    visible={this.state.resetPwdModal.visible}
                    onOk={this.handleResetPwdSubmit}
                    okText="确认修改"
                    confirmLoading={this.state.resetPwdModal.confirmLoading}
                    onCancel={this.handleResetPwdCancle}
                >
                    <ResetPwdForm resetInfo={this.state.resetInfo} wrappedComponentRef={(resetPwdForm) => { this.resetPwdForm = resetPwdForm; }} />
                </Modal>
                <Modal title="用户信息更新"
                    width={880}
                    visible={this.state.updateInfoModal.visible}
                    onOk={this.handleUpdateInfoSubmit}
                    okText="确认修改"
                    confirmLoading={this.state.updateInfoModal.confirmLoading}
                    destroyOnClose={true}
                    onCancel={() => {
                        this.setState({
                            updateInfoModal: {
                                ...this.state.updateInfoModal,
                                visible: false
                            }
                        })
                    }}
                    destroyOnClose={true}
                >
                    <UpdateInfoForm updateInfo={this.state.updateInfo} wrappedComponentRef={(updateInfoForm) => { this.updateInfoForm = updateInfoForm; }} />
                </Modal>
            </div>
        );
    }

}
//创建用户表单
class CreateForm extends React.Component {
    state = {}
    //onChange 的参数（如 event）转化为控件的值 这里 file filelist
    uploadFileVal = (e) => {
        let url = "";
        if (e.file.response && e.file.response.code == 0) {
            url = e.file.response.data.showUrl || "";
        }
        return url;
    }
    //选择图片文件
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({
                uploadLoading: true
            })
        } else if (info.file.status === 'done') {
            if (info.file.response.code != 0) {
                message.error(`上传失败，${info.file.response.msg}`);
                this.setState({
                    uploadLoading: false,
                })
            } else {
                message.success(`${info.file.name} 上传成功`);
                Utils.getBase64(info.file.originFileObj, imageUrl => this.setState({
                    imageUrl,
                    uploadLoading: false,
                }));
            }
        } else if (info.file.status === 'error') {
            this.setState({
                uploadLoading: false
            })
            message.error(`${info.file.name} 上传失败，请重新上传！`);
        }
    }
    //上传文件之前的操作  图片限制
    handleBeforeUpload = (file) => {
        //console.log(file)
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
            message.error('图片不能超过10MB!');
        }
        return isLt2M;
    }
    getImageUrl=(imageUrl)=>{
        console.log(imageUrl)
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 16 }
        };
        const userNo = this.props.userNo;
        //文件上传
        const props = {
            name: 'file',
            listType: "picture-card",
            accept: "image/*",
            showUploadList: false,
            disabled: this.state.uploadLoading,
            action: UploadBaseUrl + '/att/attachment/singleUploadToDir?categoryDir=' + fileDirectory.common,
            headers: {
                authorization: 'authorization-text',
                'X-Api-Key': localStorage.getItem("X-Api-Key"),
                "X-User-Id": localStorage.getItem("X-User-Id"),
                "X-Client-Id": localStorage.getItem("browserFingerprint"),
            },
            beforeUpload: this.handleBeforeUpload,
            onChange: this.handleChange,
        };
        const uploadButton = (
            <div>
                <Icon type={this.state.uploadLoading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        const imageUrl = this.state.imageUrl;
        return (
            <Form>
                <FormItem label="名称" {...formItemLayout}>
                    {
                        getFieldDecorator('name', {
                            rules: [{ required: true, message: '请填写名称!' }],
                        })(
                            <Input type="text" placeholder="名称" />
                        )
                    }
                </FormItem>
                <FormItem label="登录帐号" {...formItemLayout}>
                    {
                        getFieldDecorator('account', {
                            rules: [{ required: true, message: '请填写登录帐号!' }],
                        })(
                            <Input type="text" placeholder="登录帐号" />
                        )
                    }
                </FormItem>
                <FormItem label="登录密码" {...formItemLayout}>
                    {
                        getFieldDecorator('password', {
                            rules: [{ required: true, message: '请输入登录密码!' }],
                        })(
                            <Input type="password" placeholder="登录密码" />
                        )
                    }
                </FormItem>
                <FormItem label="用户序号" {...formItemLayout}>
                    {
                        getFieldDecorator('no', {
                            rules: [{ required: true, message: '请填写用户序号!' }],
                            initialValue: userNo
                        })(
                            <Input type="text" placeholder="用户序号" />
                        )
                    }
                </FormItem>
                <FormItem label="性别" {...formItemLayout}>
                    {
                        getFieldDecorator('gender', {
                            initialValue: "SECRECY"
                        })(
                            <RadioGroup>
                                <Radio value="MAN">男</Radio>
                                <Radio value="WOMAN">女</Radio>
                                <Radio value="SECRECY">保密</Radio>
                            </RadioGroup>
                        )
                    }
                </FormItem>
                <FormItem label="头像" {...formItemLayout}>
                    {
                        getFieldDecorator('headPortrait', {
                            getValueFromEvent: this.uploadFileVal,
                        })(
                            <UploadImage getImageUrl={this.getImageUrl}/>
                        )
                    }
                </FormItem>
                
                <FormItem label="头像" {...formItemLayout}>
                    {
                        getFieldDecorator('headPortrait', {
                            getValueFromEvent: this.uploadFileVal,
                        })(
                            <Upload
                                {...props}
                            >
                                {imageUrl ? <img src={imageUrl} alt="icon" className="preview-img" /> : uploadButton}
                            </Upload>
                        )
                    }
                </FormItem>
                <FormItem label="邮箱" {...formItemLayout}>
                    {
                        getFieldDecorator('email', {
                            rules: [{
                                type: 'email', message: '邮箱格式不正确!',
                            }],
                        })(
                            <Input type="text" placeholder="邮箱" />
                        )
                    }
                </FormItem>
                <FormItem label="联系电话" {...formItemLayout}>
                    {
                        getFieldDecorator('tel', {
                            rules: [{ pattern: telRegex, message: "联系电话格式不正确" }]
                        })(
                            <Input type="text" placeholder="联系电话（格式：区号-12341234）" />
                        )
                    }
                </FormItem>
                <FormItem label="手机号码" {...formItemLayout}>
                    {
                        getFieldDecorator('mobile', {
                            rules: [{ pattern: mobileRegex, message: "手机号格式不正确" }]
                        })(
                            <Input type="text" placeholder="手机号码（格式：13612341234）" />
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
CreateForm = Form.create({})(CreateForm);
//重置密码表单
class ResetPwdForm extends React.Component {
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 16 }
        };
        const resetInfo = this.props.resetInfo;
        return (
            <Form>
                <FormItem {...formItemLayout} style={{ display: 'none' }}>
                    {
                        getFieldDecorator('id', {
                            initialValue: resetInfo.id
                        })(
                            <Input type="hidden" placeholder="密码" />
                        )
                    }
                </FormItem>
                <FormItem label="帐号" {...formItemLayout}>
                    <div>{resetInfo.account}</div>
                </FormItem>
                <FormItem label="密码" {...formItemLayout}>
                    {
                        getFieldDecorator('password', {
                            rules: [{ required: true, message: '请填写密码!' }],
                            initialValue: ''
                        })(
                            <Input type="password" placeholder="密码" />
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
ResetPwdForm = Form.create({})(ResetPwdForm);
//更新用户信息表单
class UpdateInfoForm extends React.Component {
    state = {}
    componentWillMount() {
        if (!this.state.positionData) {
            this.positionRequest();
        }
        if (!this.state.jobTitleData) {
            this.jobTitleRequest();
        }
        const updateInfo = this.props.updateInfo;
        let params = {
            id: updateInfo.id
        }
        this.detailsRequest(params);
    }
    componentDidMount() {
        //组件渲染之后调用，只调用一次

    }
    //职位获取
    positionRequest = () => {
        let params = {
            key: '职位'
        }
        Axios.dataRequest({
            block: '/setting',
            url: '/quickSelect/query',
            params: params,
        }).then((data) => {
            console.log(data)
            this.setState({
                positionData: data.data
            })
        }).catch((error) => {
            console.log(error);
        })
    }
    //职称获取
    jobTitleRequest = () => {
        let params = {
            key: '职称'
        }
        Axios.dataRequest({
            block: '/setting',
            url: '/quickSelect/query',
            params: params,
        }).then((data) => {
            console.log(data)
            this.setState({
                jobTitleData: data.data
            })
        }).catch((error) => {
            console.log(error);
        })
    }
    //查询用户详情请求
    detailsRequest = (params) => {
        this.setState({
            loading: true,
            loadingTxt: '用户信息拉取中...'
        })
        Axios.dataRequest({
            block: '/hr',
            url: '/user/detail',
            params: params,
        }).then((data) => {
            console.log(data)
            let userDetails = data.data;
            this.setState({
                loading: false,
                userDetails,
            }, () => {
                //设置头像回显
                let userDetails = this.state.userDetails || {};
                let headPortrait = userDetails.headPortrait
                this.setState({
                    imageUrl: headPortrait
                })
                this.props.form.setFieldsValue({
                    'headPortrait': headPortrait,
                });
            })
        }).catch((error) => {
            this.setState({ loading: false })
            console.log(error);
        })
    }
    //onChange 的参数（如 event）转化为控件的值 这里 file filelist
    uploadFileVal = (e) => {
        let url = "";
        if (e.file.response && e.file.response.code == 0) {
            url = e.file.response.data.showUrl || "";
        }
        return url;
    }
    //选择图片文件
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({
                uploadLoading: true
            })
        } else if (info.file.status === 'done') {
            if (info.file.response.code != 0) {
                message.error(`上传失败，${info.file.response.msg}`);
                this.setState({
                    uploadLoading: false,
                })
            } else {
                message.success(`${info.file.name} 上传成功`);
                Utils.getBase64(info.file.originFileObj, imageUrl => this.setState({
                    imageUrl,
                    uploadLoading: false,
                }));
            }
        } else if (info.file.status === 'error') {
            this.setState({
                uploadLoading: false
            })
            message.error(`${info.file.name} 上传失败，请重新上传！`);
        }
    }
    //上传文件之前的操作  图片限制
    handleBeforeUpload = (file) => {
        //console.log(file)
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
            message.error('图片不能超过10MB!');
        }
        return isLt2M;
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 }
        };
        const userDetails = this.state.userDetails || '';
        const jobTitleData = this.state.jobTitleData || [];
        const positionData = this.state.positionData || [];
        const jobTitleOptions = jobTitleData.map((item) => {
            return <Option key={item.id} value={item.value}>{item.text}</Option>
        })
        const positionOptions = positionData.map((item) => {
            return <Option key={item.id} value={item.value}>{item.text}</Option>
        })
        //文件上传
        const props = {
            name: 'file',
            listType: "picture-card",
            accept: "image/*",
            showUploadList: false,
            disabled: this.state.uploadLoading,
            action: UploadBaseUrl + '/att/attachment/singleUploadToDir?categoryDir=' + fileDirectory.common,
            headers: {
                authorization: 'authorization-text',
                'X-Api-Key': localStorage.getItem("X-Api-Key"),
                "X-User-Id": localStorage.getItem("X-User-Id"),
                "X-Client-Id": localStorage.getItem("browserFingerprint"),
            },
            beforeUpload: this.handleBeforeUpload,
            onChange: this.handleChange,
        };
        const uploadButton = (
            <div>
                <Icon type={this.state.uploadLoading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        const imageUrl = this.state.imageUrl;
        return (
            <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                <div className="layout-form">
                    <div className="left-div">
                        <Form>
                            <FormItem {...formItemLayout} style={{ display: 'none' }}>
                                {
                                    getFieldDecorator('id', {
                                        initialValue: userDetails.id
                                    })(
                                        <Input type="hidden" placeholder="" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="帐号" {...formItemLayout}>
                                <div>{userDetails.account}</div>
                            </FormItem>
                            <FormItem label="名称" {...formItemLayout}>
                                {
                                    getFieldDecorator('name', {
                                        rules: [{ required: true, message: '请填写名称!' }],
                                        initialValue: userDetails.name
                                    })(
                                        <Input type="text" placeholder="名称" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="用户序号" {...formItemLayout}>
                                {
                                    getFieldDecorator('userNo', {
                                        rules: [{ required: true, message: '请填写用户序号!' }],
                                        initialValue: userDetails.userNo
                                    })(
                                        <Input type="text" placeholder="用户序号" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="性别" {...formItemLayout}>
                                {
                                    getFieldDecorator('gender', {
                                        initialValue: userDetails.gender
                                    })(
                                        <RadioGroup>
                                            <Radio value="MAN">男</Radio>
                                            <Radio value="WOMAN">女</Radio>
                                            <Radio value="SECRECY">保密</Radio>
                                        </RadioGroup>
                                    )
                                }
                            </FormItem>
                            <FormItem label="头像" {...formItemLayout}>
                                {
                                    getFieldDecorator('headPortrait', {
                                        getValueFromEvent: this.uploadFileVal,
                                    })(
                                        <Upload
                                            {...props}
                                        >
                                            {imageUrl ? <img src={imageUrl} alt="icon" className="preview-img" /> : uploadButton}
                                        </Upload>
                                    )
                                }
                            </FormItem>
                            <FormItem label="邮箱" {...formItemLayout}>
                                {
                                    getFieldDecorator('email', {
                                        rules: [{
                                            type: 'email', message: '邮箱格式不正确!',
                                        }],
                                        initialValue: userDetails.email
                                    })(
                                        <Input type="text" placeholder="邮箱" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="联系电话" {...formItemLayout}>
                                {
                                    getFieldDecorator('tel', {
                                        rules: [{ pattern: telRegex, message: "联系电话格式不正确" }],
                                        initialValue: userDetails.tel
                                    })(
                                        <Input type="text" placeholder="联系电话（格式：区号-12341234）" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="手机号码" {...formItemLayout}>
                                {
                                    getFieldDecorator('mobile', {
                                        rules: [{ pattern: mobileRegex, message: "手机号格式不正确" }],
                                        initialValue: userDetails.mobile
                                    })(
                                        <Input type="text" placeholder="手机号码（格式：13612341234）" />
                                    )
                                }
                            </FormItem>
                        </Form>
                    </div>
                    <div className="right-div">
                        <Form>
                            <FormItem label="真实姓名" {...formItemLayout}>
                                {
                                    getFieldDecorator('realname', {
                                        initialValue: userDetails.realname
                                    })(
                                        <Input type="text" placeholder="真实姓名" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="生日" {...formItemLayout}>
                                {
                                    getFieldDecorator('birthDate', {
                                        initialValue: moment(userDetails.birthDate)
                                    })(
                                        <DatePicker
                                            format="YYYY-MM-DD"
                                            placeholder="生日"
                                        />
                                    )
                                }
                            </FormItem>
                            <FormItem label="行业工作时间" {...formItemLayout}>
                                {
                                    getFieldDecorator('beginIndustryJobTime', {
                                        initialValue: moment(userDetails.beginIndustryJobTime)
                                    })(
                                        <DatePicker
                                            format="YYYY-MM-DD"
                                            placeholder="行业工作时间"
                                        />
                                    )
                                }
                            </FormItem>
                            <FormItem label="身份证号码" {...formItemLayout}>
                                {
                                    getFieldDecorator('idcard', {
                                        rules: [{ pattern: idCardRegex, message: "身份证号码格式不正确" }],
                                        initialValue: userDetails.idcard
                                    })(
                                        <Input type="text" placeholder="身份证号码" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="教育背景" {...formItemLayout}>
                                {
                                    getFieldDecorator('eduBackground', {
                                        initialValue: userDetails.eduBackground
                                    })(
                                        <Input type="text" placeholder="教育背景" />
                                    )
                                }
                            </FormItem>
                            <FormItem label="入职时间" {...formItemLayout}>
                                {
                                    getFieldDecorator('hiredate', {
                                        initialValue: moment(userDetails.hiredate)
                                        //initialValue:moment('2018-08-08')
                                    })(
                                        <DatePicker
                                            format="YYYY-MM-DD"
                                            placeholder="入职时间"
                                        />
                                    )
                                }
                            </FormItem>
                            <FormItem label="职称" {...formItemLayout}>
                                {
                                    getFieldDecorator('jobTitle', {
                                        initialValue: userDetails.jobTitle
                                    })(
                                        <Select placeholder="请选择职称" style={{ minWidth: 160 }}>
                                            {jobTitleOptions}
                                        </Select>
                                    )
                                }
                            </FormItem>
                            <FormItem label="职位" {...formItemLayout}>
                                {
                                    getFieldDecorator('position', {
                                        initialValue: userDetails.position
                                    })(
                                        <Select placeholder="请选择职位" style={{ minWidth: 160 }}>
                                            {positionOptions}
                                        </Select>
                                    )
                                }
                            </FormItem>
                        </Form>
                    </div>
                </div>
            </Spin>
        );
    }
}
UpdateInfoForm = Form.create({})(UpdateInfoForm);

//搜索表单
class FilterForm extends React.Component {
    handleFilterSubmit = () => {
        let fieldsValue = this.props.form.getFieldsValue();
        this.props.filterSubmit(fieldsValue);
    }
    //重置
    reset = () => {
        this.props.form.resetFields();
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="inline">
                <FormItem label="状态">
                    {
                        getFieldDecorator('state', {
                            initialValue: ""
                        })(
                            <Select placeholder="用户状态" style={{ minWidth: 100 }}>
                                <Option key="ALL" value="">全部</Option>
                                <Option key="VALID" value="VALID">有效的</Option>{/*有效的与禁用相对*/}
                                <Option key="DISABLE" value="DISABLE">禁用的</Option>
                                <Option key="INACTIVE" value="INACTIVE">未激活</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="关键词">
                    {
                        getFieldDecorator('keywords', {
                        })(
                            <Input type="text" placeholder="关键词" />
                        )
                    }
                </FormItem>
                <FormItem>
                    <Button type="primary" style={{ margin: '0 10px 0 0' }} onClick={this.handleFilterSubmit}>查询</Button>
                    <Button onClick={this.reset}>重置</Button>
                </FormItem>
            </Form>
        );
    }
}
FilterForm = Form.create({})(FilterForm);